import axios from 'axios'
import { ElMessage } from 'element-plus'

const request = axios.create({
  baseURL: '/api',
  timeout: 10000
})

// 请求拦截器
request.interceptors.request.use(
  config => {
    // 从localStorage获取token
    const token = localStorage.getItem('token')
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  response => {
    const res = response.data
    if (res?.code === 200) {
      return res
    }
    // 401: 未登录或token过期
    if (res?.code === 401) {
      ElMessage.error(res.message || '请先登录')
      localStorage.removeItem('token')
      window.location.href = '/login'
      return Promise.reject(new Error(res.message || '请先登录'))
    }
    // 403: 无权限
    if (res?.code === 403) {
      ElMessage.error(res.message || '无权限访问')
      // 对于已进入主框架的页面，回退到首页
      if (location.pathname.startsWith('/main')) {
        window.location.href = '/main/shou'
      }
      return Promise.reject(new Error(res.message || '无权限访问'))
    }
    ElMessage.error(res?.message || '请求失败')
    return Promise.reject(new Error(res?.message || '请求失败'))
  },
  error => {
    if (error.response) {
      const status = error.response.status
      const msg = error.response.data?.message
      if (status === 401) {
        ElMessage.error(msg || '请先登录')
        localStorage.removeItem('token')
        window.location.href = '/login'
      } else if (status === 403) {
        ElMessage.error(msg || '无权限访问该资源')
        if (location.pathname.startsWith('/main')) {
          window.location.href = '/main/shou'
        }
      } else {
        ElMessage.error(msg || '请求失败')
      }
    } else {
      ElMessage.error('网络错误，请稍后重试')
    }
    return Promise.reject(error)
  }
)

export default request